//
//  PPAlbumContentPrivacyViewController.m
//  pickpic
//
//  Created by Jinxiao on 9/11/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPAlbumContentPrivacyViewController.h"

#import "PPAlbumContentViewDataSource.h"

#import "PPAlbumContentPrivacyTableViewCell.h"

#import "PPFriendsManager.h"

#import "PPContactsModel.h"

@interface PPAlbumContentPrivacyViewController () <UITableViewDelegate, UITableViewDataSource>
@property (readwrite, nonatomic, strong) NSNumber *privacy;
@property (readwrite, nonatomic, strong) PPAbstractTableView *tableView;
@property (readwrite, nonatomic, strong) NSArray <PPContactsModel *> *contacts;
@property (readwrite, nonatomic, strong) NSMutableArray *selectedUserIDs;
@end

@implementation PPAlbumContentPrivacyViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.automaticallyAdjustsScrollViewInsets = YES;

    _contacts = [PPContactsModel where:@{@"currentUserID" : DGCurrentAccount.userID, @"relationship" : @1}];;

    _tableView = [[PPAbstractTableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView registerNib:[UINib nibWithNibName:@"PPAlbumContentPrivacyTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_tableView];

    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = [UIColor clearColor];
    headerView.frame = CGRectMake(0, 0, CGFLOAT_MIN, 16);
    _tableView.tableHeaderView = headerView;

    UIView *footerView = [[UIView alloc] init];
    footerView.backgroundColor = [UIColor clearColor];
    footerView.frame = CGRectMake(0, 0, CGFLOAT_MIN, CGFLOAT_MIN);
    _tableView.tableFooterView = footerView;

    __weak typeof(self)weakSelf = self;
    [self setNavigationLeftTitle:@"取消" action:^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];

    [self setNavigationRightTitle:@"完成" titleColor:[UIColor colorWithRGBHex:0xffdd17] action:^{
        weakSelf.dataSource.privacy = weakSelf.privacy;
        weakSelf.dataSource.privacyUserIDs = weakSelf.selectedUserIDs;
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    _tableView.frame = self.view.bounds;
}

- (void)setDataSource:(PPAlbumContentViewDataSource *)dataSource {
    _dataSource = dataSource;

    _privacy = dataSource.privacy;

    _selectedUserIDs = [NSMutableArray arrayWithArray:_dataSource.privacyUserIDs];

    [_tableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 5;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    PPAlbumPrivacy privacy = PPAlbumPrivacyNone;

    switch(section) {
        case 0: privacy = PPAlbumPrivacyAll; break;

        case 1: privacy = PPAlbumPrivacyOnlyMe; break;

        case 2: privacy = PPAlbumPrivacyFriends; break;

        case 3: privacy = PPAlbumPrivacySelectedVisible; break;

        case 4: privacy = PPAlbumPrivacySelectedInvisible; break;
            
        default: break;
    }

    switch(section) {
        case 0:
        case 1:
        case 2: {
            return 0;
        }

        case 3:
        case 4: {
            if(_privacy.integerValue == privacy) {
                return _contacts.count;
            } else {
                return 0;
            }
        }

        default:
            return 0;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 46;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    PPAlbumContentPrivacyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];

    PPContactsModel *contact = [_contacts safeObjectAtIndex:indexPath.row];

    if(contact.avatarURLString.length > 0) {
        [cell.avatarView sd_setImageWithURL:[NSURL URLWithString:contact.avatarURLString] placeholderImage:nil options:SDWebImageRetryFailed];
    } else {
        cell.avatarView.image = [UIImage imageNamed:@"icon-person-70"];
    }

    cell.nameLabel.text = contact.name;

    BOOL selected = NO;

    for(PPUserID selectedUserID in _selectedUserIDs) {
        if(selectedUserID.integerValue == contact.userID.integerValue) {
            selected = YES;
            break;
        }
    }

    if(selected) {
        cell.indicatorView.image = [UIImage imageNamed:@"radio-select-36"];
    } else {
        cell.indicatorView.image = [UIImage imageNamed:@"radio-normal-36"];
    }

    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIControl *headerView = [[UIControl alloc] init];
    headerView.backgroundColor = [UIColor whiteColor];
    headerView.frame = CGRectMake(0, 0, tableView.width, [self tableView:tableView heightForHeaderInSection:section]);

    [headerView addTopBorderWithColor:kLineColor andWidth:kLineWidth];

    NSString *text = nil;
    PPAlbumPrivacy privacy = PPAlbumPrivacyNone;

    switch(section) {
        case 0: privacy = PPAlbumPrivacyAll; text = @"所有人可见"; break;

        case 1: privacy = PPAlbumPrivacyOnlyMe; text = @"仅自己可见"; break;

        case 2: privacy = PPAlbumPrivacyFriends; text = @"所有朋友可见"; break;

        case 3: privacy = PPAlbumPrivacySelectedVisible; text = @"选中的朋友可见"; break;

        case 4: privacy = PPAlbumPrivacySelectedInvisible; text = @"选中的朋友不可见"; break;

        default: break;
    }

    if(privacy == _privacy.integerValue) {
        UIImageView *indicatorView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"radio"]];
        indicatorView.centerY = headerView.height/2;
        indicatorView.left = 16;
        [headerView addSubview:indicatorView];
    }

    UILabel *label = [[UILabel alloc] init];
    label.text = text;
    label.textColor = [UIColor colorWithRGBHex:0x323232];
    label.font = [UIFont systemFontOfSize:16];
    [label sizeToFit];
    label.left = 44;
    label.centerY = headerView.height/2;
    [headerView addSubview:label];

    if(privacy == PPAlbumPrivacySelectedVisible || privacy == PPAlbumPrivacySelectedInvisible) {
        UIImageView *indicatorView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"next"]];
        indicatorView.centerY = headerView.height/2;
        indicatorView.right = headerView.width - 16;
        [headerView addSubview:indicatorView];
    }

    __weak typeof(self)weakSelf = self;
    [headerView setActionBlock:^(UIControl *control) {
        [weakSelf headerView:control withIndex:section privacyDidPressed:privacy];
    } forControlEvents:UIControlEventTouchUpInside];

    return headerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    PPContactsModel *contact = [_contacts safeObjectAtIndex:indexPath.row];

    BOOL selected = NO;

    for(PPUserID selectedUserID in _selectedUserIDs) {
        if(selectedUserID.integerValue == contact.userID.integerValue) {
            selected = YES;
            break;
        }
    }

    if(selected) {
        [_selectedUserIDs removeObject:contact.userID];
    } else {
        [_selectedUserIDs addObject:contact.userID];
    }

    [_tableView reloadData];
}

- (void)headerView:(UIControl *)headerView withIndex:(NSInteger)index privacyDidPressed:(PPAlbumPrivacy)privacy {
    _privacy = @(privacy);

    [_selectedUserIDs removeAllObjects];

    [_tableView reloadData];
}

@end
